package com.example.big_orange2.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.big_orange2.authorization.manager.TokenManager;
import com.example.big_orange2.common.Result;
import com.example.big_orange2.entity.Staff;
import com.example.big_orange2.entity.User;
import com.example.big_orange2.entity.code;
import com.example.big_orange2.mapper.UserMapper;
import com.example.big_orange2.utils.RSAutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {
    @Resource
    UserMapper userMapper;

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    WeChatService weChatService;

    //引用公钥
    @Value("${publicKey}")
    private String publicKey;
    //引用私钥
    @Value("${privateKey}")
    private String privateKey;


    public Result<String> login(@RequestBody User user) {
        Result<String> result=new Result<>();
        RSAutils rsautils=new RSAutils();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone", user.getTelephone());
        queryWrapper.eq("passwords",rsautils.decode(user.getPasswords(),privateKey) );
        User res = userMapper.selectOne(queryWrapper);
        if (res == null) {
            result.setResult("fail");
            result.setMessage("用户名或密码错误");
        }else if(res.getActive()=="1"){
            result.setResult("fail");
            result.setMessage("用户名不存在");
        }else{
            String token=tokenManager.getToken(user);
            result.setData(token);
            result.setCode("200");
            result.setToken(token);
            result.setMessage("登录验证成功");
            result.setResult("success");
        }
        return  result;

    }

    public Result<?> add(@RequestBody User user){//?是泛型，表示任意类型
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone", user.getTelephone());
        RSAutils rsautils=new RSAutils();
        user.setPasswords( rsautils.decode(user.getPasswords(),privateKey));
        User res = userMapper.selectOne(queryWrapper);
        if(res!=null){
            return Result.error("-1", "该电话已注册用户");
        }else{
            userMapper.insert(user);
            return Result.success();//返回操作情况
        }

    }
    public Result<?> get3rd(@RequestBody code code){
        Result<String> result =new Result<>();
        List<String> list = new ArrayList<>();
        try{

            list = weChatService.get3rdSession(code.getCode(),"1");
            result.setToken(list.get(1));
            result.setResult("success");
        }catch (Exception e){
            result.setResult("fail");
            result.setMessage(e.getMessage());
        }
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        wrapper.eq(User::getOpenid,list.get(0));
        wrapper.eq(User::getActive,"0");
        List<User> Loanhandle = userMapper.selectList(wrapper);//
        System.out.println(Loanhandle);
        if(Loanhandle.size() == 0){
            System.out.println("为空情况，无openid对应用户");
            result.setResult("fail");
            result.setMsg("无该微信用户对应后端用户");
            return result;
        }else{
            System.out.println("非空，且查找用户为："+Loanhandle);
        }
        Result<?> results = result.success(Loanhandle.get(0));
        results.setToken(list.get(1));
        results.setResult("success");

        return  results;
    }

    public Result<?> logind_t(@RequestBody User user) {


        Result<?> result=new Result<>();
        Result<?> results = new Result<>();
        RSAutils rsautils=new RSAutils();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone", user.getTelephone());
        queryWrapper.eq("passwords", rsautils.decode(user.getPasswords(),privateKey) );
        queryWrapper.eq("active","0");
        User res = userMapper.selectOne(queryWrapper);
        if (res == null) {
            result.setResult("fail");
            result.setMessage("用户名或密码错误");
        }else{
            String token=tokenManager.getToken(user);
            results = result.success(res);
            results.setToken(token);
            results.setResult("success");
            results.setMessage("验证成功");
        }
        System.out.println(results);
        return  results;

    }
    public Result<?> setUserOpenid(@RequestBody User user, @PathVariable String code) {
        Result<?> result = new Result<>();
        List<String> list = new ArrayList<>();
        System.out.println(user);
        System.out.println(code);
        try{
            list = weChatService.get3rdSession(code,"1");
            result.setToken(list.get(1));
            result.setResult("success");
        }catch (Exception e){
            result.setResult("fail");
            result.setMessage(e.getMessage());
        }
//        System.out.println(list);
//        user.setOpenid();
//        userMapper.updateById(user);
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("telephone",user.getTelephone());
        User users = new User();
        users.setOpenid(list.get(0));
        userMapper.update(users, updateWrapper);
        result.setCode("0");
        result.setMsg("修改成功");

        return result;
    }

}
